<?php

namespace App\Http\Controllers;

use App\Utils\Response;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class UserController extends Controller
{

    // 根据id查询用户
    public function getUserById($id)
    {
        $user = User::find($id);
        if (!$user) {
            return Response::fail(null,"用户未找到");
        }
        return Response::ok($user,null);
    }

    // 根据手机号查询用户
    public function getUserByMobile($mobile)
    {
        $user = User::where('mobile', $mobile)->first();
        if (!$user) {
            return Response::fail(null,"用户未找到");
        }
        return Response::ok($user,null);
    }

    // 根据手机号注册用户
    public function registerUser(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'mobile' => 'required|unique:user|max:255',
        ]);

        if ($validator->fails()) {
            return Response::fail(null, $validator->errors());
        }

        $user = new User;
        $user->name = Str::random(10);; // 生成随机姓名
        $user->mobile = $request->mobile;
        $user->save();

        return Response::ok($user,null);
    }

    // 根据name、手机号模糊查询列表
    public function searchUsers(Request $request)
    {
        $search = $request->get('search');
        $users = User::where('name', 'like', "%$search%")
            ->orWhere('mobile', 'like', "%$search%")
            ->get();
        return Response::ok($users,null);
    }

    // 根据id删除用户
    public function deleteUser($id)
    {
        $user = User::find($id);
        if (!$user) {
            return Response::fail(null,"用户未找到");
        }
        $user->delete();
        return Response::ok(null,"删除成功");
    }
}
